package com.thinvent.remotepassword.main;

import com.thinvent.remotepassword.util.SimilarityUtil;

import java.io.IOException;
import java.sql.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class DmDatabaseUtils {

    // 数据库连接信息
    private static final String URL = "jdbc:dm://119.84.98.78:5237";
    private static final String USERNAME = "DMTIMER1";
    private static final String PASSWORD = "sichuang2020";

    // 加载达梦 JDBC 驱动
    static {
        try {
            Class.forName("dm.jdbc.driver.DmDriver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 获取数据库连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }

    // 查询所有 CQProject
    public static List<CQProject> findAllCQProjects(Connection connection) {
        List<CQProject> projects = new ArrayList<>();
        String query = "SELECT id, GJ_PRO_NAME, GJ_PRO_ORG, GJ_MAIN_BUILD_SCALE FROM DR.CQ_PROJECT";

        try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                CQProject project = new CQProject();
                project.setId(resultSet.getString("ID"));
                project.setGj_pro_name(resultSet.getString("GJ_PRO_NAME"));
                project.setGj_pro_org(resultSet.getString("GJ_PRO_ORG"));
                project.setGj_main_build_scale(resultSet.getString("GJ_MAIN_BUILD_SCALE"));
                projects.add(project);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return projects;
    }

    public static List<CQBasePro> findAllCQBaseProsGroupedByGjProName(Connection connection, int segments) {
        List<CQBasePro> basePros = new ArrayList<>();
        int pageSize = 0; // 每段的数据量
        int totalRows = 0; // 总数据量

        // 查询总数据量
        String countQuery = "SELECT COUNT(*) AS total FROM DR.CQ_BASE_PRO";
        try (PreparedStatement countStatement = connection.prepareStatement(countQuery)) {
            ResultSet countResult = countStatement.executeQuery();
            if (countResult.next()) {
                totalRows = countResult.getInt("total");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 计算每段的数据量
        pageSize = (int) Math.ceil((double) totalRows / segments);

        // 开始分段查询
        for (int i = 0; i < segments; i++) {
            int offset = i * pageSize;

            String query = "SELECT id, gj_pro_name, gj_pro_org, gj_main_build_scale FROM DR.CQ_BASE_PRO ORDER BY gj_pro_name LIMIT ? OFFSET ?";

            try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
                preparedStatement.setInt(1, pageSize);
                preparedStatement.setInt(2, offset);

                ResultSet resultSet = preparedStatement.executeQuery();

                while (resultSet.next()) {
                    CQBasePro basePro = new CQBasePro();
                    basePro.setId(resultSet.getString("ID"));
                    basePro.setGj_pro_name(resultSet.getString("GJ_PRO_NAME"));
                    basePro.setGj_pro_org(resultSet.getString("GJ_PRO_ORG"));
                    basePro.setGj_main_build_scale(resultSet.getString("GJ_MAIN_BUILD_SCALE"));
                    basePros.add(basePro);

                }

                // 更新页码
                System.out.println("当前查询到第：" + (i + 1) + "段");
            } catch (SQLException e) {
                e.printStackTrace();
                break; // 在出现异常时停止循环
            }
        }

        return basePros;
    }

    public static List<CombinedData> convertResultMapToList(Map<CQProject, List<CQBasePro>> resultMap) {
        List<CombinedData> dataList = new ArrayList<>();
        for (Map.Entry<CQProject, List<CQBasePro>> entry : resultMap.entrySet()) {
            CQProject cqProject = entry.getKey();
            List<CQBasePro> cqBasePros = entry.getValue();

            if (cqBasePros == null || cqBasePros.isEmpty()) {
                // 当 cqBasePros 为空或不存在时，只添加与 CQProject 相关的字段
                CombinedData data = new CombinedData(
                        cqProject.getId(),
                        cqProject.getGj_pro_name(),
                        cqProject.getGj_pro_org(),
                        cqProject.getGj_main_build_scale(),
                        null, // target 相关字段设置为 null
                        null,
                        null,
                        null
                );
                dataList.add(data);
            } else {
                for (CQBasePro cqBasePro : cqBasePros) {
                    CombinedData data = new CombinedData(
                            cqProject.getId(),
                            cqProject.getGj_pro_name(),
                            cqProject.getGj_pro_org(),
                            cqProject.getGj_main_build_scale(),
                            cqBasePro.getId(),
                            cqBasePro.getGj_pro_name(),
                            cqBasePro.getGj_pro_org(),
                            cqBasePro.getGj_main_build_scale()
                    );
                    dataList.add(data);
                }
            }
        }
        return dataList;
    }
}
